package com.yy.web.pm.until;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yy.web.pm.user.domain.OpenIdUser;
import com.yy.web.pm.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

@Component
public class JwtAuthFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

        // 获取请求路径
        String requestURI = request.getRequestURI();

        // 放行特定路径
        if ("/pm/date/auth/wechat".equals(requestURI) || "/pm/date/register".equals(requestURI)) {
            chain.doFilter(request, response);
            return;
        }

        // 检查 Token
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotBlank(token) && token.startsWith("Bearer ")) {
            try {
                String openid = jwtUtils.verifyToken(token.substring(7));

                // 创建简易认证对象
                UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
                        new OpenIdUser(openid), // 包装openid
                        null,
                        Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")) // 基础权限
                );

                SecurityContextHolder.getContext().setAuthentication(auth);
            } catch (Exception e) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token无效");
                return;
            }
        }

        chain.doFilter(request, response);
    }
}
